package com.meitianhui.convenitenbuy.module.home.presenter;

import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;

import com.alipay.sdk.app.PayTask;
import com.google.gson.Gson;
import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.base.BaseResponse;
import com.meitianhui.convenitenbuy.config.InfoProvider;
import com.meitianhui.convenitenbuy.http.ResponseObserver;
import com.meitianhui.convenitenbuy.main.model.bean.EventBean;
import com.meitianhui.convenitenbuy.module.home.contract.OpenFightGroupContract;
import com.meitianhui.convenitenbuy.module.home.http.HomeApiDataSource;
import com.meitianhui.convenitenbuy.module.home.model.bean.GoodsInfoDetail;
import com.meitianhui.convenitenbuy.module.home.ui.activity.JoinFightGroupActivity;
import com.meitianhui.convenitenbuy.module.home.ui.activity.OpenFightGroupActivity;
import com.meitianhui.convenitenbuy.module.wallet.http.WalletApiDataSource;
import com.meitianhui.convenitenbuy.module.wallet.model.AlipayResultBean;
import com.meitianhui.convenitenbuy.module.wallet.model.PayResultBean;
import com.meitianhui.convenitenbuy.module.wallet.model.RechargeBackInfoBean;
import com.meitianhui.convenitenbuy.util.LogUtils;
import com.meitianhui.convenitenbuy.util.RxBus;
import com.meitianhui.convenitenbuy.util.SystemUtils;
import com.meitianhui.convenitenbuy.util.TipUtils;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class OpenFightGroupPresenter implements OpenFightGroupContract.Presenter {

    private OpenFightGroupActivity mContext;
    private JoinFightGroupActivity mJContext;
    private OpenFightGroupContract.View mView;
    private final IWXAPI wxApi;

    public OpenFightGroupPresenter(OpenFightGroupContract.View view,
                                   OpenFightGroupActivity context) {
        this.mView = view;
        this.mContext = context;
        wxApi = WXAPIFactory.createWXAPI(context, Constants.WX_APP_ID, true);
    }

    public OpenFightGroupPresenter(OpenFightGroupContract.View view,
                                   JoinFightGroupActivity context) {
        this.mView = view;
        this.mJContext = context;
        wxApi = WXAPIFactory.createWXAPI(context, Constants.WX_APP_ID, true);
    }

    @Override
    public void getGoodsInfoDetail(String goodsId, String activityId, String service) {
        Map<String, String> map = new HashMap<>();
        map.put("goods_id", goodsId);
        map.put("activity_type", "ladder");
        map.put("activity_id", activityId);
        String paramJson = new Gson().toJson(map);

        HomeApiDataSource.getInstance()
                .getGoodsInfoDetail(InfoProvider.getUserToken(App.getInstance()).getUser_token(),
                        service, paramJson)
                .subscribe(new ResponseObserver<BaseResponse<GoodsInfoDetail>>(mContext, true) {
                    @Override
                    public void onSuccess(BaseResponse<GoodsInfoDetail> response) {
                        mView.getGoodsInfoDetailSuccess(response.data);
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        super.onFail(code, msg);
                        mView.getGoodsInfoDetailFail(code, msg);
                    }
                });
    }

    @Override
    public void getJoinGoodsInfoDetail(String activityId, String service) {
        Map<String, String> map = new HashMap<>();
        map.put("activity_id", activityId);
        String paramJson = new Gson().toJson(map);

        HomeApiDataSource.getInstance()
                .getJoinGoodsInfoDetail(InfoProvider.getUserToken(App.getInstance()).getUser_token(),
                        service, paramJson)
                .subscribe(new ResponseObserver<BaseResponse<GoodsInfoDetail>>(mJContext, true) {
                    @Override
                    public void onSuccess(BaseResponse<GoodsInfoDetail> response) {
                        mView.getGoodsInfoDetailSuccess(response.data);
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        super.onFail(code, msg);
                        mView.getGoodsInfoDetailFail(code, msg);
                    }
                });
    }

    @Override
    public void openGroupPay(int payWay, String goodId, String storeId,
                             GoodsInfoDetail.Convenient convenient) {
        Map<String, String> params = new HashMap<>();
        params.put("data_source", Constants.CUSTOM_APP);
        params.put("member_id", InfoProvider.getUserToken(App.getInstance()).getMember_id());
        params.put("member_type_key", "consumer");
        params.put("goods_id", goodId);
        params.put("min_num", convenient.getTs_min_num());//成团要求
        params.put("expiried_hour", convenient.getTs_date());
        params.put("stores_id", storeId);
        String mobile = InfoProvider.getUserInfo(App.getInstance()).getMobile();
        if (!TextUtils.isEmpty(mobile)) {
            params.put("member_mobile", mobile);
        }
        params.put("activity_type", "ladder");
        params.put("received_mode", "pick_up");//送货方式 门店自提
        if (payWay == 0) {
            params.put("payment_way_key", Constants.PAYMENT_WAY_05);
        } else if (payWay == 1) {
            params.put("payment_way_key", Constants.ALIPAY_APY);
        } else if (payWay == 2) {
            params.put("payment_way_key", Constants.WECHAT_APY);
        }
        params.put("amount", convenient.getDiscount_price());
        String paramJson = new Gson().toJson(params);

        WalletApiDataSource.getInstance()
                .getRechargeOrder(InfoProvider.getUserToken(App.getInstance()).getUser_token(),
                        "finance.tsActivityCreatePay", paramJson)
                .subscribe(new ResponseObserver<BaseResponse<RechargeBackInfoBean>>(mContext, true) {
                    @Override
                    public void onSuccess(BaseResponse<RechargeBackInfoBean> response) {
                        RechargeBackInfoBean result = response.data;
                        if (payWay == 1) {
                            wakeUpAliPay(mContext, result);
                        } else {
                            wakeUpWeChat(mContext, result);
                        }
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        super.onFail(code, msg);
                        mView.payFail(code, msg);
                    }
                });
    }

    @Override
    public void joinGroupPay(int payWay, String activityId, GoodsInfoDetail.Convenient convenient) {
        Map<String, String> params = new HashMap<>();
        params.put("data_source", Constants.CUSTOM_APP);
        params.put("member_id", InfoProvider.getUserToken(App.getInstance()).getMember_id());
        params.put("member_type_key", "consumer");
        String mobile = InfoProvider.getUserInfo(App.getInstance()).getMobile();
        if (!TextUtils.isEmpty(mobile)) {
            params.put("member_mobile", mobile);
        }
        params.put("activity_type", "ladder");
        if (payWay == 0) {
            params.put("payment_way_key", Constants.PAYMENT_WAY_05);
        } else if (payWay == 1) {
            params.put("payment_way_key", Constants.ALIPAY_APY);
        } else if (payWay == 2) {
            params.put("payment_way_key", Constants.WECHAT_APY);
        }
        params.put("activity_id", activityId);
        params.put("amount", convenient.getDiscount_price());
        String paramJson = new Gson().toJson(params);

        WalletApiDataSource.getInstance()
                .getRechargeOrder(InfoProvider.getUserToken(App.getInstance()).getUser_token(),
                        "finance.tsOrderPay", paramJson)
                .subscribe(new ResponseObserver<BaseResponse<RechargeBackInfoBean>>(mJContext, true) {
                    @Override
                    public void onSuccess(BaseResponse<RechargeBackInfoBean> response) {
                        RechargeBackInfoBean result = response.data;
                        if (payWay == 1) {
                            wakeUpAliPay(mJContext, result);
                        } else {
                            wakeUpWeChat(mJContext, result);
                        }
                    }

                    @Override
                    public void onFail(int code, String msg) {
                        super.onFail(code, msg);
                        mView.payFail(code, msg);
                    }
                });
    }

    private void wakeUpAliPay(Activity context, RechargeBackInfoBean bean) {
        String orderInfo = bean.getAlipay_params();
        Observable.create(new ObservableOnSubscribe<String>() {
            @Override
            public void subscribe(ObservableEmitter<String> emitter) throws Exception {
                PayTask alipay = new PayTask(context);
                String result = alipay.pay(orderInfo, true);
                emitter.onNext(result);
            }
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread()).subscribe(new Consumer<String>() {
            @Override
            public void accept(String s) throws Exception {
                AlipayResultBean payResult = new AlipayResultBean(s);
                String resultInfo = payResult.getResult();
                String resultStatus = payResult.getResultStatus();
                // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                if (TextUtils.equals(resultStatus, "9000")) {
                    TipUtils.showToast(App.getInstance(), App.getInstance().getString(R.string.wallet_change_recharge_success), 1);
                    RxBus.get().post(new PayResultBean(Constants.PAY_FIGHT_GROUP_SUCCESS));
                    RxBus.get().post(new EventBean(Constants.EVENT_TYPE_REFRESH));
                } else {
                    // 判断resultStatus 为非“9000”则代表可能支付失败
                    // “8000”代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，
                    // 最终交易是否成功以服务端异步通知为准（小概率状态）
                    if (TextUtils.equals(resultStatus, "8000")) {
                        TipUtils.showToast(App.getInstance(), mContext.getString(R.string.wallet_change_recharge_confirming), 3);
                    } else {
                        // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                        TipUtils.showToast(App.getInstance(), context.getString(R.string.wallet_change_recharge_fail));

                    }
                }
            }
        });
    }

    public void wakeUpWeChat(Context context, RechargeBackInfoBean result) {
        boolean ifInstall = SystemUtils.isWXAppInstalledAndSupported(context, result.getAppid());
        if (!ifInstall) {
            TipUtils.showToast(App.getInstance(), context.getString(R.string.wallet_change_recharge_order_wechat_uninstall));
            return;
        }
        PayReq req = new PayReq();
        req.appId = result.getAppid();
        req.nonceStr = result.getNoncestr();
        req.packageValue = result.getPackageValue();
        req.partnerId = result.getPartnerid();
        req.prepayId = result.getPrepayid();
        req.timeStamp = result.getTimestamp();
        req.sign = result.getSign();
        wxApi.registerApp(result.getAppid());
        wxApi.sendReq(req);
        LogUtils.d("--------------------", "eeeeeeeeeeee");
    }

    @Override
    public void attachView(Object view) {
    }

    @Override
    public void detachView() {
    }

}
